package com.ericxu.weixin.msg;

import javax.servlet.ServletInputStream;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

public abstract class WeiXinMessage {
	protected String toUserName;
	protected String frmUserName;
	protected String createTime;
	protected String msgType;
	protected String msgId;
	
	public static WeiXinMessage createMessage(ServletInputStream in) {
		WeiXinMessage msg = null;
		SAXReader reader = new SAXReader();
		try {
			Document doc = reader.read(in);
			String msgType = doc.selectSingleNode("//MsgType").getText();
			if ("text".equalsIgnoreCase(msgType)) {
				msg = new TextWeiXinMessage(doc);
			} else {
				msg = new InvalidWeiXinMessage(doc);
			}
		} catch (DocumentException e1) {
			e1.printStackTrace();
		}
		return msg;
	}
	
	public WeiXinMessage(Document doc) {
		if (doc != null) {
			this.frmUserName = doc.selectSingleNode("//FromUserName").getText();
			this.toUserName = doc.selectSingleNode("//ToUserName").getText();
			this.createTime = doc.selectSingleNode("//CreateTime").getText();
			this.msgType = doc.selectSingleNode("//MsgType").getText();
			this.msgId = doc.selectSingleNode("//MsgId").getText();
		}
	}
	
	public void setToUserName(String name) {
		this.toUserName = name;
	}
	
	public String getToUserName() {
		return this.toUserName;
	}
	
	public void setFromUserName(String name) {
		this.frmUserName = name;
	}
	
	public String getFromUserName() {
		return this.frmUserName;
	}
	
	public void setCreateTime(String time) {
		this.createTime = time;
	}
	
	public String getCreateTime() {
		return this.createTime;
	}
	
	public void setMsgType(String type) {
		this.msgType = type;
	}
	
	public String getMsgType() {
		return this.msgType;
	}
	
	public void setMsgId(String id) {
		this.msgId = id;
	}
	
	public String getMsgId() {
		return this.msgId;
	}
	
	@Override
	public String toString() {
		String retString = "FromUserName:" + this.frmUserName + "\r\n"
				+ "ToUserName:" + this.toUserName + "\r\n"
				+ "CreateTime:" + this.createTime + "\r\n"
				+ "MsgType:" + this.msgType + "\r\n"
				+ "MsgId:" + this.msgId;
		return retString;
	}
	
	public abstract WeiXinMessage excute();
}
